<!-- 广告管理 -->
<template>
    <div class="common-layout">
        <el-backtop :bottom="50" target=".main" ref="backTop" :visibility-height="10"></el-backtop>
        <el-container>
            <el-header>
                <el-space>
                    <el-select class="frame" placeholder="请选择广告状态" v-model="seacherData.status">
                        <el-option v-for="item in advertStatus" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                    <el-select class="frame" placeholder="请选择广告类型" v-model="seacherData.type">
                        <el-option v-for="item in advertTypeList" :key="item.value" :label="item.name"
                            :value="item.value" />
                    </el-select>
                    <el-button :icon="Search" type="primary" @click="search()">查找</el-button>
                    <el-button :icon="Plus" type="primary" @click="addRole();">添加</el-button>
                </el-space>
            </el-header>
            <el-main>
                <div class="el-scrollbar__wrap metaBox">
                    <el-backtop :bottom="100" ref="backTop" :visibility-height="5" target=".metaBox .el-scrollbar__wrap" />
                    <!-- 表格组件 -->
                    <el-table :data="tableData" border style="width: 100%;height: 100%;" class="scrollbar-demo-item"
                        v-loading="listLoading" element-londing-text="正在加载中...">
                        <el-table-column prop="id" label="广告ID" align="center" />
                        <el-table-column prop="title" label="广告标题" align="center" />
                        <el-table-column prop="imgUrl" label="广告图片" align="center">
                            <template #default="scope">
                                <el-popover trigger="hover" placement="right" v-if="scope.row.type < 5">
                                    <template #reference>
                                        <el-image :src="scope.row.imgUrl" style="width:35px;height:50px;" />
                                    </template>
                                    <template #default>
                                        <el-image v-if="scope.row.imgUrl" :src="scope.row.imgUrl"
                                            style="width:148px;height:180px;" />
                                    </template>
                                </el-popover>
                                <el-tag type="info" v-else>类型无需图片</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="广告类型" align="center">
                            <template #default="scope">
                                <div v-for="item in advertTypeList" :key="item.value">
                                    <el-tag v-if="item.value == scope.row.type">{{ item.name }}</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="广告状态" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.status == 0 ? 'danger' : 'success'">
                                    {{ scope.row.status == 0 ? '冻结' : '激活' }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unionType" label="关联类型" align="center">
                            <template #default="scope">
                                <div v-for="item in advertType" :key="item.value">
                                    <el-tag v-if="scope.row.unionType == item.value">{{ item.name }}</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unionValue" label="关联值【ID】" align="center" />

                        <el-table-column prop="gmtCreate" label="创建时间" align="center">
                            <!-- 时间转换 -->
                            <template #default="scope">
                                {{ traversalTime(scope.row.gmtCreate) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template #default="scope">
                                <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-main>
            <el-footer>
                <Paging v-bind="pagination" @page-change="pageChange" />
            </el-footer>
        </el-container>
    </div>

    <!-- 对话框组件 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" destroy-on-close @opened="openfrom">
        <!-- 修改功能表单组件 -->
        <el-form ref="ruleFormRef" :model="dataForm" status-icon :rules="rules" class="demo-ruleForm" label-width="200px">
            <el-form-item prop="title" label="广告标题">
                <el-input class="fix_input" v-model.trim="dataForm.title" type="text" autocomplete="off"
                    placeholder="请输入广告标题" />
            </el-form-item>
            <el-form-item label="广告类型" prop="type">
                <el-select class="frame" placeholder="请选择广告类型" v-model="dataForm.type" @change="handleChange">
                    <el-option v-for="item in advertTypeList" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="广告图片" prop="imgUrl" id="upload" ref="uploadRef" class="is-required"
                v-show="advertTypeList.find(val => val.value == dataForm.type)?.picRequire">
                <el-upload class="avatar-uploader" action="http://192.168.1.188:8080/upload/admin" :headers="headers" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="dataForm.imgUrl" :src="dataForm.imgUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="广告状态" prop="status">
                <el-switch v-model="dataForm.status" size="large" :active-value="1" :inactive-value="0" />
            </el-form-item>

            <el-form-item label="关联类型" prop="unionType">
                <el-select class="frame" placeholder="请选择关联类型" v-model="dataForm.unionType" :disabled="!dataForm.type"
                    @change="dataForm.unionValue = undefined">
                    <el-option v-for="item in advertType" :key="item.value" :label="item.name"
                        :disabled='!handleDisabled || !handleDisabled.unionTypes?.includes(item.value)'
                        :value="item.value" />
                </el-select>

            </el-form-item>

            <el-form-item label="商品" prop="unionValue" class="is-required" dataForm v-if="dataForm.unionType == '1'">
                <div>
                    <el-cascader :options="options" clearable :props="props" v-model="dataForm.unionValue" />
                </div>
            </el-form-item>
            <el-form-item label="类目" prop="unionValue" class="is-required" dataForm v-if="dataForm.unionType == '2'">
                <div>
                    <el-cascader :options="classPptions" clearable :props="prop" v-model="dataForm.unionValue" />
                </div>
            </el-form-item>
            <el-form-item label="关键字" prop="unionValue" dataForm v-if="dataForm.unionType == '3'">
                <el-input v-model.trim="dataForm.unionValue" style="width:300px" placeholder="请输入关键字" clearable />
            </el-form-item>
            <el-form-item label="页面功能" prop="unionValue" class="is-required" dataForm v-if="dataForm.unionType == '4'">
                <el-select placeholder="请选择功能页面" v-model="dataForm.unionValue">
                    <el-option v-for="item in advertRouter" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="sure(ruleFormRef);">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessageBox, ElNotification, type FormInstance, type UploadProps } from 'element-plus'
import { post } from '@/utils/http';
import { computed, nextTick, onMounted, reactive, ref } from 'vue';
import Paging from '@/components/paging/Paging.vue'
import { ClassPagination, ClassAdvert } from '#/index';
import { ElMessage } from "element-plus"
import { handleTime, traversalTime } from '@/utils/ProcessingTime'
import cookie from 'js-cookie'
import { theColorFn } from '@/utils/theColorFn';
// 数据初始化
onMounted(() => {
    init()
})

// 控制对话框组件的显示隐藏
const dialogVisible = ref(false)
const options: Array<any> = reactive([])    //类目树结构
const classPptions: Array<any> = reactive([]) //类目树
const backTop = ref()                                   //回到顶部
const pagination = reactive(new ClassPagination())      //分页
let tableData: TypeAdvert[] = reactive([])               //表格数据
let listLoading = ref(false)            //加载效果
const dialogTitle = ref("")             //判断添加和修改
const uploadRef = ref()
/**
 * 表单数据
 */
// 添加传递的数据

const dataForm = reactive(new ClassAdvert())
/**
 * 添加时清空参数
 */
let newForms = { ...dataForm }

/**
 * 表单验证
 */
const rules = {
    title: [
        { required: true, message: "广告标题不得为空！", trigger: 'change' },
    ],
    type: [
        { required: true, message: "请选择广告类型！", trigger: 'change' }
    ],
    unionType: [
        { required: true, message: "请选择关联类型！", trigger: 'change' }
    ],
    unionValue: [
        { required: true, message: "此项不能为空!", trigger: 'change' }
    ]
}

/**
* 搜索所需的数据
*/
const seacherData = reactive({
    type: '',
    status: undefined,
})
/**
* 商品树配置选项
*/
const props = {
    checkStrictly: false,
    emitPath: false,
    children: "children",
    value: "id",
    label: "label"
}
/**
 * 类目树配置选项
 */
const prop = {
    checkStrictly: true,
    emitPath: false,
    children: "childrenList",
    value: "id",
    label: "title"
}
/**
 * 广告类型
 */
const advertTypeList = [
    { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: '轮播' },
    { value: 2, unionTypes: [2], picRequire: true, name: '分类精选' },
    { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: '横幅' },
    { value: 4, unionTypes: [1, 2, 3, 4], picRequire: true, name: '首页轮播下5按钮' },
    { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: '公告' },
    { value: 9, unionTypes: [1], picRequire: false, name: '商品推荐' }
]
/**
 * 关联类型
 */
const advertType = [
    { value: 1, name: "商品" },
    { value: 2, name: "类目" },
    { value: 3, name: "关键字" },
    { value: 4, name: "功能页面" }
];
/**
 * 广告状态
 */
const advertStatus = [
    { value: 0, name: "冻结" },
    { value: 1, name: "激活" }
];
/**
 * 功能页面
 */
const advertRouter = [
    { value: "/pages/product/groupshop", label: "团购列表", name: ' ' },
    { value: "/pages/coupon/list", label: "优惠券列表", name: ' ' },
]

// 搜索操作
function search() {
    init()
}

getCategory()
getCommodity()
/**
 * 请求商品数据
 */
function getCommodity() {
    post({
        _gp: "admin.product",
        _mt: "getSpuBigTree"
    }).then(res => {
        console.log(res.data)
        let { errmsg, errno } = res
        if (200 == errno) {
            options.length = 0
            options.push(...res.data)

        } else {
            ElMessage.error(errmsg)
        }

    })
}
/**
 * 请求类目数据
 */
function getCategory() {
    post({
        _gp: "admin.category",
        _mt: "categoryTree"
    }).then(res => {
        let { errmsg, errno } = res
        if (200 == errno) {
            classPptions.length = 0
            classPptions.push(...res.data)
        }
        else {
            ElMessage.error(errmsg)
        }
    })
}
// 添加操作
function addRole() {
    dialogTitle.value = "创建"
    Object.assign(dataForm, newForms)
    dialogVisible.value = true;
    console.log(dataForm)
}
/**
 * 获取初始化数据，用于渲染页面
 */
function init() {
    listLoading.value = true
    // 请求管理员列表需要传递的参数
    let couponListData = reactive({
        _gp: "admin.advert",
        _mt: "list",
        // title: seacherData.title,
        type: seacherData.type,
        status: seacherData.status,//用户状态
        pageNo: pagination.page,//当前页码
        limit: pagination.limit//每页页码长度
    })
    // 请求管理员列表接口拿到管理员列表信息
    post(couponListData).then(res => {
        console.log("====管理员数据======");
        console.log(res);
        let { data: { total, items }, errno, errmsg } = res
        if (200 === errno) {
            pagination.total = total
            console.log(items);


            tableData.length = 0;

            tableData.push(...items)
            listLoading.value = false
            nextTick(() => {
                backTop.value.$el.click?.()
            })
        } else {
            ElMessage.error(errmsg)
        }
    }).catch(err => {
        console.log(err);

    })


}

const ruleFormRef = ref<FormInstance>()
//子传父的自定义事件
function pageChange(e: TypePage) {
    pagination.page = e.page
    pagination.limit = e.limit
    init()
}

/**
 * 获取修改前的数据
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleEdit = (index: number, row: any) => {
    // dialogTitle.value = "修改"
    // Object.assign(dataForm, { ...row, adId: row.id })
    // dialogVisible.value = true;
    // console.log(dataForm)


    dialogTitle.value = "修改"

    if (row.unionType == 1 || row.unionType == 2) {
        row.unionValue = parseInt(row.unionValue as string)
    }
    Object.assign(dataForm, { ...row, adId: row.id })
    nextTick(() => {
        dialogVisible.value = true
        getCommodity()//商品
        getCategory()//类目
    })

}

/**
 * 删除操作
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleDelete = (index: number, row: TypeAdvert) => {

    let data = {
        _gp: 'admin.advert',
        _mt: 'delete',
        type: row.type,
        adId: row.id
    }

    ElMessageBox.confirm('真的要删除吗？')
        .then(() => {
            post(data).then(res => {
                console.log(res);

                let { errno } = res
                if (200 === errno) {
                    ElMessage.success('删除成功')
                    init()
                }
            }).catch(err => {
                console.log(err);
            })
        })
        .catch(() => {
            ElMessage.error("取消删除！")
        })

}

/**
 * 添加和修改功能
 * @param formEl 表单验证结果
 */
function sure(formEl: FormInstance | undefined) {

    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log("=====要提交的表单数据=====");
            console.log(dataForm);
            if (dataForm.type == 6 || dataForm.type == 9) {
                dataForm.imgUrl = "https://www.baidu.com/img/flexible/logo/pc/result.png"
            }
            if (dataForm.imgUrl == '') {
                ElNotification.error('请选择广告图片')
                return
            }
            let data = {
                _gp: 'admin.advert',
                _mt: dataForm.adId ? 'edit' : 'create',
                ...dataForm
            }
            post(data).then(res => {
                console.log(res);

                let { errno } = res
                if (200 === errno) {
                    dialogVisible.value = false
                    ElMessage.success(dataForm.adId ? '修改成功' : '添加成功')
                    init()
                }
            }).catch(err => {
                console.log(err);
            })
        } else {
            return false
        }
    })
}

/**
 * 表单重置
 * @param formEl 表单验证结果
 */
function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
}


/**
 * 上传图片添加请求头
 */
const headers = reactive({
    AdminToken: cookie.get('token')
})

/**
 * 上传图片
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    dataForm.imgUrl = response.url
    dataForm.imgUrl = response.url // 得到上传图片成功的路径
    theColorFn(dataForm.imgUrl, (callback: string) => {
        dataForm.color = callback
    }) // 计算得到图片平均色
    console.log(dataForm.color);

    init()
}

function openfrom() {
    uploadRef.value.$el.style.backgroundColor = dataForm.color;
}

/**
 * 验证图片格式
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片格式只能是 JPG格式 !')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

/**
 * 判断禁用
 */
let handleDisabled = computed(() => {
    if (dataForm.type) {
        return advertTypeList.find(item => item.value == dataForm.type)
    } else { return '' }
})

/**
 * 切换时清空节点
 */
function handleChange() {
    dataForm.unionType = undefined
    if (dataForm.adId == 0) {

        dataForm.color = ''
        uploadRef.value.$el.style.backgroundColor = dataForm.color;
        dataForm.imgUrl = ''

    }
}
</script>
  

<style scoped lang="less">
.metaBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
    text-align: center;
}

.fix_input {
    width: 200px;
}

.treechile {
    position: relative;
    right: 0px;
    color: red;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>